package com.lanswon.qzsmk.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.slf4j.LoggerFactory;

import ch.qos.logback.classic.Logger;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lanswon.qzsmk.exception.ApplicationException;
import com.lanswon.qzsmk.exception.SystemException;

public class HttpUtil {

	private static Logger logger = (Logger) LoggerFactory.getLogger(HttpUtil.class);

	public static InputStream getInputStream(String url1) {
		InputStream input = null;
		HttpURLConnection conn = getHttpURLConnection(url1);
		try {
			input = conn.getInputStream();
		} catch (IOException e) {
			e.printStackTrace();
			 String msg1="IO流异常";
				logger.error(msg1);
				throw new SystemException(SystemException.IOException, msg1);

		}
		return input;
	}

	public static int getResponseCode(String url1) {
		int responseCode = 0;
		HttpURLConnection conn = getHttpURLConnection(url1);
		try {
			responseCode = conn.getResponseCode();
		} catch (IOException e) {
			e.printStackTrace();
			 String msg1="IO流异常";
				logger.error(msg1);
				throw new SystemException(SystemException.IOException, msg1);

		}

		return responseCode;
	}

	private static HttpURLConnection getHttpURLConnection(String url1) {
		HttpURLConnection conn = null;
		try {
			URL url = new URL(url1);
			conn = (HttpURLConnection) url.openConnection();
		} catch (MalformedURLException e) {
			e.printStackTrace();
			 String msg1="IO流异常";
				logger.error(msg1);
				throw new SystemException(SystemException.IOException, msg1);

		} catch (IOException e) {
			e.printStackTrace();
			 String msg1="IO流异常";
				logger.error(msg1);
				throw new SystemException(SystemException.IOException, msg1);

		}

		return conn;
	}

	public static List<String> getStreamString(InputStream tInputStream) {
		 List<String> list = new ArrayList<String>();

		if (tInputStream != null) {
			try {
				BufferedReader tBufferedReader = new BufferedReader(new InputStreamReader(tInputStream,"UTF-8"));
//				StringBuffer tStringBuffer = new StringBuffer();
				String sTempOneLine = new String("");
				while ((sTempOneLine = tBufferedReader.readLine()) != null) {
					if(sTempOneLine!=""){
//						tStringBuffer.append(sTempOneLine+"\n");
						list.add(sTempOneLine);
					}
					
				}
//				return tStringBuffer.toString();
				
			} catch (IOException ex) {
				ex.printStackTrace();
				 String msg1="IO流异常";
					logger.error(msg1);
					throw new SystemException(SystemException.IOException, msg1);

			}
		}
		return list;

	}
	
	public static JSONObject doPost(String url,List<NameValuePair> parameForToken){
		 String result = null;
		 logger.debug("url="+url);
	        CloseableHttpClient httpclient = HttpClients.createDefault();
	        CloseableHttpResponse response = null;
	        try {
	            //创建post请求
	            HttpPost httpPost = new HttpPost(url);
	             // 设置请求和传输超时时间  
	            RequestConfig requestConfig = RequestConfig.custom()  
	                    .setSocketTimeout(20000).setConnectTimeout(20000).build();
	            httpPost.setConfig(requestConfig); 
	            //httpPost.setHeader(new BasicHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"));
	            //httpPost.setHeader(new BasicHeader("Accept", "text/plain;charset=utf-8"));

	            // 提交参数发送请求
	            UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(parameForToken,Consts.UTF_8);
	            httpPost.setEntity(urlEncodedFormEntity);
	            response = httpclient.execute(httpPost);
	            // 得到响应信息
	            int statusCode = response.getStatusLine().getStatusCode();
	            // 判断响应信息是否正确
	            if (statusCode != HttpStatus.SC_OK) {
	                // 终止并抛出异常
	                httpPost.abort();
	                throw new RuntimeException("HttpClient,error status code :" + statusCode);
	            }
	            HttpEntity entity = response.getEntity();
	            if (entity != null) {
	                //result = EntityUtils.toString(entity);//不进行编码设置
	                result = EntityUtils.toString(entity, "UTF-8");
	            }
	            logger.debug("result="+result);
	            EntityUtils.consume(entity);
	            return JSON.parseObject(result);
	        } catch (Exception e) {
	        	e.printStackTrace();
	        	String msg = "网络通信异常";
	            logger.error(msg);
	            throw new SystemException(SystemException.communication_exception, msg);
	        } finally {
	            //关闭所有资源连接
	        	try {
	            if (response != null) {
	                    response.close();
	            }
	            if (httpclient != null) {
	                    httpclient.close();
	            }
	        	} catch (IOException e) {
	        		e.printStackTrace();
	        		String msg = "网络通信异常";
		            logger.error(msg);
		            throw new SystemException(SystemException.communication_exception, msg);
                }
	        }
	}
	
	
	/**
	 * get请求
	 * @return
	 * @throws ApplicationException 
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static JSONObject doGetJSON(String url,List<NameValuePair> parameForToken) throws ApplicationException{
		String result = null;
		JSONObject jsonObject=null;
		CloseableHttpResponse response=null;
		CloseableHttpClient  httpClient=HttpClients.createDefault();
		try{
		String parameStr = null;    
        parameStr = EntityUtils.toString(new UrlEncodedFormEntity(parameForToken));
        //拼接参数
        StringBuffer sb = new StringBuffer();
        sb.append(url);
        sb.append("?");
        sb.append(parameStr);    
        logger.debug("url="+sb.toString());
		HttpGet httpGet=new HttpGet(sb.toString());
		// 设置请求和传输超时时间  
        RequestConfig requestConfig = RequestConfig.custom()  
                .setSocketTimeout(2000).setConnectTimeout(2000).build();  
        httpGet.setConfig(requestConfig); 
		response=httpClient.execute(httpGet);
		// 得到响应信息
        int statusCode = response.getStatusLine().getStatusCode();
        // 判断响应信息是否正确
        if (statusCode != HttpStatus.SC_OK) {
            // 终止并抛出异常
            httpGet.abort();
            throw new ApplicationException(SystemException.communication_exception,"通信异常");
        }
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            result = EntityUtils.toString(entity);
        }

        EntityUtils.consume(entity);
        jsonObject=JSON.parseObject(result);
		return jsonObject;
		}catch(Exception exception){
			exception.printStackTrace();
			String msg = "网络通信异常";
            logger.error(msg);
            throw new SystemException(SystemException.communication_exception, msg);
		}finally {
            //关闭所有资源连接
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (httpClient != null) {
                try {
                	httpClient.close();
                } catch (IOException e) {
                	e.printStackTrace();
                	String msg = "网络通信异常";
    	            logger.error(msg);
    	            throw new SystemException(SystemException.communication_exception, msg);
                }
            }
        }

	}
	
	public static void main(String[] args) {
		//String g="http://192.168.0.12:9999/qzsmk/resource/makeCardFile/makeCardCompany/江南制卡厂/RBJM1001803060002.txt";
		String g="http://192.168.0.12:9999/qzsmk/resource/makeCardFile/bank/JS_BANK/BP/BP-JS1806300001.txt";
		System.out.println(File.separator);
		System.out.println(g.substring(g.lastIndexOf("/")));
		InputStream in =getInputStream(g);
		List<String> d =getStreamString(in);
		for(String f:d){
			String[] gg = StringUtils.splitPreserveAllTokens(f, "|");
			for(int j=0;j<gg.length;j++){
				System.out.println(j+"="+gg[j]);
				if(j==gg.length-1){
					System.out.println("gg="+Arrays.toString(gg));
				}
			}
		}
		
	
	
	}
}
